package snaptest.repo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import snaptest.core.exception.RepositoryException;

public class FileRepo {
	
	private FileIO fileIO = new FileIO();

	private final String rootDir;

	public FileRepo(String rootDir) {
		this.rootDir = rootDir;
	}

	public void setFileIO(FileIO fileIO) {
		this.fileIO = fileIO;
	}

	public String load(String fileName) {
		FilePath file = prependRootDir(fileName);
		try {
			return fileIO.load(file.getPath());
		} catch (IOException e) {
			throw new RepositoryException("Could not read file: " + file, e);
		}
	}

	private FilePath prependRootDir(String fileName) {
		return new FilePath(fileName).prependDirectory(rootDir);
	}

	public void save(String fileName, String content) {
		FilePath file = prependRootDir(fileName);
		try {
			fileIO.createFile(file.removeLastElement().getPath(), file.getLastElement());
			fileIO.save(file.getPath(), content);
		} catch (IOException e) {
			throw new RepositoryException("Could not save to file: " + file, e);
		}
	}
	
	public boolean exist(String fileName) {
		return fileIO.fileExists(prependRootDir(fileName).getPath());
	}

	public List<String> scan() {
		List<String> result = new ArrayList<String>();
		for(String entry:scan(rootDir)) {
			result.add(new FilePath(entry).removeFirstElement().getPath());
		}
		return result;
	}
	
	private List<String> scan(String dir) {
		List<String> result = new ArrayList<String>();
		FileDirSplitter fileDirSplitter = new FileDirSplitter(dir);
		result.addAll(fileDirSplitter.getTextFiles());
		for(String subDir : fileDirSplitter.getSubDirs()) {
			result.addAll(scan(subDir));
		}
		return result;
	}

}
